# coding: utf-8


import os
import set_env_path  # 请勿删除


from datetime import date

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Base = declarative_base()
engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
Session = sessionmaker(bind=engine)
session = Session()


def update_user_marketing_info():
    """
    create by ld_wu 2018-05-16
    已分级工程进行拉新信息更新
    """
    select_sql = """
        select 
            user.id,
            user.mobile,
            user.area_id
        from
            user
        where
            wx_openid=''
            and sms_marketing_obj=1
            and sms_marketing_level in (1, 2)
            and deleted_at = 0
            and is_virt=0
    """

    select_info = """
        select
             id
        from user_marketing_info
        where
             user_id = :user_id
    """

    create_info = """
        insert into
        user_marketing_info
        (
            view_count,
            total_send_count,
            bid_click_count, 
            attend_click_count,
            mobile, 
            user_id, 
            area_id, 
            status,
            push_date
        )
        VALUES (0, 0, 0, 0, :mobile, :user_id, :area_id, 10, :push_date)
    """

    res = session.execute(
        select_sql
    ).fetchall()

    today = date.today()

    for user in res:
        info = session.execute(
            select_info,
            dict(
                user_id=user[0]
            )
        ).fetchone()
        if not info:
            print(user)
            session.execute(
                create_info,
                dict(
                    user_id=user[0],
                    mobile=user[1],
                    area_id=str(user[2])[:2] + '0000',
                    push_date=str(today)
                )
            )
        else:
            print(info)

    session.commit()

if __name__ == '__main__':
    update_user_marketing_info()
